package gu.sql2java;

import java.util.AbstractMap;
import java.util.Collections;
import java.util.Set;


import com.google.common.collect.Sets;

import static com.google.common.base.Preconditions.*;

class RowMapView extends AbstractMap<String, Object> {

	private final BaseRow row;
	private final Set<Entry<String, Object>> entrySet;

	public RowMapView(BaseRow bean) {
		this.row = checkNotNull(bean,"bean is null");
		Set<Entry<String, Object>> s = Sets.newLinkedHashSet();
		for(int i =0; i < bean.metaData.columnCount; ++i){
			s.add(new RowEntry(i));
		}
		entrySet = Collections.unmodifiableSet(s);
		
	}

	@Override
	public Set<Entry<String, Object>> entrySet() {
		return entrySet;
	}

	@Override
	public Object put(String key, Object value) {
		int columnId = row.metaData.columnIDOf(key);		
		checkArgument(columnId >=0, "INVALID column name %s",key);
		Object old = row.getValue(columnId);
		row.setValue(columnId, value);
		return old;
	}

	private class RowEntry implements Entry<String,Object>{
		private final int columnId;
		
		public RowEntry(int columnId) {
			super();
			this.columnId = columnId;
		}

		@Override
		public String getKey() {
			return row.metaData.columnNames.get(columnId);
		}

		@Override
		public Object getValue() {
			return row.getValue(columnId);
		}

		@Override
		public Object setValue(Object value) {
			Object old = row.getValue(columnId);
			row.setValue(columnId, value);
			return old;
		}}
}
